<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">


<meta name="google-site-verification" content="E9deYnivN5MuHMuIfiMZZfS0alv-d_0UjcwjBL79lGU" />



<meta name="baidu-site-verification" content="iHYWJxscwD" />










<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />








  <meta name="baidu-site-verification" content="true" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="学习笔记,量化投资,kaggle竞赛,深度学习,pytorch," />










<meta name="description" content="本文主要参考kaggle上的两篇文章：Deep Learning Tutorial for BeginnersPytorch Tutorial for Deep Learning Lovers不是全文翻译，算是我的学习笔记吧。先看Deep Learning Tutorial for Beginners。深度学习，是一种直接从数据中学习特征的机器学习技术。（Deep learning: One of">
<meta property="og:type" content="article">
<meta property="og:title" content="量化投资学习笔记98——kaggle量化投资比赛记录7-深度学习及pytorch">
<meta property="og:url" content="https://zwdnet.github.io/2021/01/20/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B098%E2%80%94%E2%80%94kaggle%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E6%AF%94%E8%B5%9B%E8%AE%B0%E5%BD%957-%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0%E5%8F%8Apytorch/index.html">
<meta property="og:site_name" content="赵瑜敏的口腔医学专业学习博客">
<meta property="og:description" content="本文主要参考kaggle上的两篇文章：Deep Learning Tutorial for BeginnersPytorch Tutorial for Deep Learning Lovers不是全文翻译，算是我的学习笔记吧。先看Deep Learning Tutorial for Beginners。深度学习，是一种直接从数据中学习特征的机器学习技术。（Deep learning: One of">
<meta property="og:locale">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/data.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/02.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/03.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/04.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/05.jpg">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/06.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/07.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/08.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/09.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/10.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/11.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/12.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg">
<meta property="article:published_time" content="2021-01-20T22:41:04.000Z">
<meta property="article:modified_time" content="2021-01-23T23:57:54.000Z">
<meta property="article:author" content="赵瑜敏">
<meta property="article:tag" content="学习笔记">
<meta property="article:tag" content="量化投资">
<meta property="article:tag" content="kaggle竞赛">
<meta property="article:tag" content="深度学习">
<meta property="article:tag" content="pytorch">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/data.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zwdnet.github.io/2021/01/20/量化投资学习笔记98——kaggle量化投资比赛记录7-深度学习及pytorch/"/>





  <title>量化投资学习笔记98——kaggle量化投资比赛记录7-深度学习及pytorch | 赵瑜敏的口腔医学专业学习博客</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">赵瑜敏的口腔医学专业学习博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zwdnet.github.io/2021/01/20/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B098%E2%80%94%E2%80%94kaggle%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E6%AF%94%E8%B5%9B%E8%AE%B0%E5%BD%957-%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0%E5%8F%8Apytorch/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="赵瑜敏的口腔医学专业学习博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">量化投资学习笔记98——kaggle量化投资比赛记录7-深度学习及pytorch</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2021-01-20T22:41:04+00:00">
                2021-01-21
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" itemprop="url" rel="index">
                    <span itemprop="name">量化投资</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  6k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  27
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文主要参考kaggle上的两篇文章：<br><a target="_blank" rel="noopener" href="https://www.kaggle.com/kanncaa1/deep-learning-tutorial-for-beginners">Deep Learning Tutorial for Beginners</a><br><a target="_blank" rel="noopener" href="https://www.kaggle.com/kanncaa1/pytorch-tutorial-for-deep-learning-lovers">Pytorch Tutorial for Deep Learning Lovers</a><br>不是全文翻译，算是我的学习笔记吧。<br>先看Deep Learning Tutorial for Beginners。<br>深度学习，是一种直接从数据中学习特征的机器学习技术。（Deep learning: One of the machine learning technique that learns features directly from data.）随着数据规模上升（如超过1百万个数据），传统机器学习技术不太适合，深度学习在准确率方面有更好的表现。深度学习应用在语音识别，图像分类，自然语言处理(nlp)或者推荐系统等方面。机器学习包括深度学习，在机器学习中，特征是人工标注的，而深度学习中特征是直接从数据中学习出来的。<br>实验数据是2062个手语数字图像，从0到9，一共10个不同的符号。0的序号从204到408,有205个。1的序号从822到1027,有206个。先只考虑0和1两个数字，因此每个分类有205个样本。尽管205个样本对深度学习来说太少了，但这是教程，就不管了。<br>先加载数据（从教程页面上下载，放到源代码目录。）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> warnings</span><br><span class="line">warnings.filterwarnings(<span class="string">&quot;ignore&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 加载数据</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">loadData</span>():</span></span><br><span class="line">    x_1 = np.load(<span class="string">&quot;./X.npy&quot;</span>)</span><br><span class="line">    y_1 = np.load(<span class="string">&quot;./Y.npy&quot;</span>)</span><br><span class="line">    img_size = <span class="number">64</span></span><br><span class="line">    plt.subplot(<span class="number">1</span>, <span class="number">2</span>, <span class="number">1</span>)</span><br><span class="line">    plt.imshow(x_1[<span class="number">260</span>].reshape(img_size, img_size))</span><br><span class="line">    plt.axis(<span class="string">&quot;off&quot;</span>)</span><br><span class="line">    plt.subplot(<span class="number">1</span>, <span class="number">2</span>, <span class="number">2</span>)</span><br><span class="line">    plt.imshow(x_1[<span class="number">900</span>].reshape(img_size, img_size))</span><br><span class="line">    plt.axis(<span class="string">&quot;off&quot;</span>)</span><br><span class="line">    plt.savefig(<span class="string">&quot;./output/data.png&quot;</span>)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/data.png"><br>把数据连接起来，并创建标签。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 把数据连接起来，并创建标签</span></span><br><span class="line">X = np.concatenate((x_1[<span class="number">204</span>:<span class="number">409</span>], x_1[<span class="number">822</span>:<span class="number">1027</span>]), axis = <span class="number">0</span>)</span><br><span class="line">z = np.zeros(<span class="number">205</span>)</span><br><span class="line">o = np.ones(<span class="number">205</span>)</span><br><span class="line">Y = np.concatenate((z, o), axis = <span class="number">0</span>).reshape(X.shape[<span class="number">0</span>], <span class="number">1</span>)</span><br><span class="line">print(X.shape)</span><br><span class="line">print(Y.shape)</span><br></pre></td></tr></table></figure>

<p>X的大小是(410, 64, 64)，即410个图片，每个图片的大小是64×64<br>Y的大小是(410, 1)，即有410个标签。<br>现在将数据划分为训练集和测试集，其中训练集占85%。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 划分训练集和测试集</span></span><br><span class="line">X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = <span class="number">0.15</span>, random_state = <span class="number">42</span>)</span><br><span class="line">number_of_train = X_train.shape[<span class="number">0</span>]</span><br><span class="line">number_of_test = X_test.shape[<span class="number">0</span>]</span><br></pre></td></tr></table></figure>

<p>将三维数据变换到二维(flatten)</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#将三维数据变换到二维</span></span><br><span class="line">X_train_flatten = X_train.reshape(number_of_train, X_train.shape[<span class="number">1</span>]*X_train.shape[<span class="number">2</span>])</span><br><span class="line">X_test_flatten = X_test.reshape(number_of_test, X_test.shape[<span class="number">1</span>]*X_test.shape[<span class="number">2</span>])</span><br><span class="line">print(<span class="string">&quot;X_train_flatten&quot;</span>, X_train_flatten.shape)</span><br><span class="line">print(<span class="string">&quot;X_test_flatten&quot;</span>, X_test_flatten.shape)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">X_train_flatten (<span class="number">348</span>, <span class="number">4096</span>)</span><br><span class="line">X_test_flatten (<span class="number">62</span>, <span class="number">4096</span>)</span><br></pre></td></tr></table></figure>

<p>将数据倒置</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">x_train = X_train_flatten.T</span><br><span class="line">x_test = X_test_flatten.T</span><br><span class="line">y_train = Y_train.T</span><br><span class="line">y_test = Y_test.T</span><br><span class="line">print(x_train.shape)</span><br><span class="line">print(x_test.shape)</span><br><span class="line">print(y_train.shape)</span><br><span class="line">print(y_test.shape)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">(<span class="number">4096</span>, <span class="number">348</span>)</span><br><span class="line">(<span class="number">4096</span>, <span class="number">62</span>)</span><br><span class="line">(<span class="number">1</span>, <span class="number">348</span>)</span><br><span class="line">(<span class="number">1</span>, <span class="number">62</span>)</span><br></pre></td></tr></table></figure>

<p>数据准备好了，下面开始干活。<br>一想到二分类问题我们首先想到的是逻辑回归。实际上逻辑回归是一个非常简单的神经网络。神经网络和深度学习是一回事。<br>计算图(computation graph)的概念<br>数学表达式的可视化。这个我这只能看到图片的一部分，折腾半天没弄下来，大家到网站上看吧。<br>逻辑回归同样有计算图。参数是权重(weight)和偏差值(bias)。权重是每个点的系数，偏差值是截距。<br>z = (w.t)x+b<br>另一个说法：z = b+px1w1+px2w2+…+px4096*w4096<br>yhead = sigmoid(z)<br>sigmoid使得z在[0,1]区间内。即一个概率值。<br>sigmoid函数的计算图<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/02.jpg"><br>为什么我们使用sigmoid函数？它返回一个概率性的结果，它是可微的，因此我们可以使用梯度下降算法。<br>下面我们初始化参数。<br>输入的数据是有4096个点的图像，每个点都有其自己的权重值。第一步是将每个点乘以其自己的权重值。初始权重值的设置有不同的方法，这里设置为0.01。偏差值为0。<br>下面是代码。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 初始化参数</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">init_params</span>(<span class="params">dimension</span>):</span></span><br><span class="line">    w = np.full((dimension, <span class="number">1</span>), <span class="number">0.01</span>)</span><br><span class="line">    b = <span class="number">0.0</span></span><br><span class="line">    <span class="keyword">return</span> w, b</span><br></pre></td></tr></table></figure>
<p>下面看前向传播过程：从输入点数据到成本的所有步骤称为前向传播(Forward Propagation)。<br>z = (w.T)x + b，w和b都知道了（.T是转置），可以算出z。将z输入sigmoid函数得到返回的概率值yhat。然后计算损失/误差函数(loss/error)。所有损失值之和就是成本。<br>下面撸代码：<br>先定义sigmoid函数。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 定义sigmoid函数</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">sigmoid</span>(<span class="params">z</span>):</span></span><br><span class="line">    y_head = <span class="number">1</span>/(<span class="number">1</span>+np.exp(-z))</span><br><span class="line">    <span class="keyword">return</span> y_head</span><br></pre></td></tr></table></figure>
<p>然后计算损失函数，使得当模型预测正确时损失值很小，而当预测错误时损失值很大。<br>下面实现前向传播过程。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment"># 前向传播过程</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">fp</span>(<span class="params">w, b, x_train, y_train</span>):</span></span><br><span class="line">    z = np.dot(w.T, x_train) + b</span><br><span class="line">    y_head = sigmoid(z)</span><br><span class="line">    loss = -y_train*np.log(y_head) - (<span class="number">1</span>-y_train)*np.log(<span class="number">1</span>-y_head)</span><br><span class="line">    <span class="comment"># 平均成本</span></span><br><span class="line">    cost = (np.<span class="built_in">sum</span>(loss))/x_train.shape[<span class="number">1</span>]</span><br><span class="line">    <span class="keyword">return</span> cost</span><br></pre></td></tr></table></figure>

<p>采用梯度下降的优化算法<br>我们需要降低成本。首先初始化权重和偏置值，这决定了初始成本。然后要更新权重和偏置值。这项技术称为梯度下降。<br>更新的方法，用老的参数值减去在该点的梯度，将该值作为参数的新的值。计算梯度的方法，是求损失函数在该点对该参数的偏导数。梯度同时确定了迭代的大小和方向。在迭代的时候，梯度要乘以一个学习率α。w’ = w - α∂L/∂w 学习率是需要权衡的，太小，学习得太慢，但不容易错过最低值。太大，学习得快，但容易错过最低值。学习率也被称为超参数(hyperparameter)，是需要选择和调参的。因此前向过程就是从参数到成本，反向过程就是从成本到参数，更新参数。怎么计算梯度及更新参数，就是数学内容了。直接上结果吧。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/03.png"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 前后向传播过程</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">fbp</span>(<span class="params">w, b, x_train, y_train</span>):</span></span><br><span class="line">    <span class="comment"># 前向传播</span></span><br><span class="line">    z = np.dot(w.T, x_train) + b</span><br><span class="line">    y_head = sigmoid(z)</span><br><span class="line">    loss = -y_train*np.log(y_head) - (<span class="number">1</span>-y_train)*np.log(<span class="number">1</span>-y_head)</span><br><span class="line">    cost = (np.<span class="built_in">sum</span>(loss))/x_train.shape[<span class="number">1</span>]</span><br><span class="line">    <span class="comment"># 后向传播过程</span></span><br><span class="line">    dw = (np.dot(x_train, ((y_head-y_train).T)))/x_train.shape[<span class="number">1</span>]</span><br><span class="line">    db = np.<span class="built_in">sum</span>(y_head-y_train)/x_train.shape[<span class="number">1</span>]</span><br><span class="line">    gradients = &#123;<span class="string">&quot;dw&quot;</span>:dw, <span class="string">&quot;db&quot;</span>:db&#125;</span><br><span class="line">    <span class="keyword">return</span> cost, gradients</span><br></pre></td></tr></table></figure>

<p>下面更新参数。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 更新参数</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">update</span>(<span class="params">w, b, x_train, y_train, learning_rate, number_of_iteration</span>):</span></span><br><span class="line">    cost_list = []</span><br><span class="line">    cost_list2 = []</span><br><span class="line">    index = []</span><br><span class="line">    <span class="comment"># 更新(学习)</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(number_of_iteration):</span><br><span class="line">        cost, gradients = fbp(w, b, x_train, y_train)</span><br><span class="line">        cost_list.append(cost)</span><br><span class="line">        <span class="comment"># 更新</span></span><br><span class="line">        w = w - learning_rate * gradients[<span class="string">&quot;dw&quot;</span>]</span><br><span class="line">        b = b - learning_rate * gradients[<span class="string">&quot;db&quot;</span>]</span><br><span class="line">        <span class="keyword">if</span> i % <span class="number">10</span> == <span class="number">0</span>:</span><br><span class="line">            cost_list2 .append(cost)</span><br><span class="line">            index.append(i)</span><br><span class="line">            print(<span class="string">&quot;第%i次迭代后的成本:%f&quot;</span> % (i, cost))</span><br><span class="line">        </span><br><span class="line">    parameters = &#123;<span class="string">&quot;weight&quot;</span>:w, <span class="string">&quot;bias&quot;</span>:b&#125;</span><br><span class="line">    plt.plot(index, cost_list2)</span><br><span class="line">    plt.savefig(<span class="string">&quot;./output/learning_curve.png&quot;</span>)</span><br><span class="line">    <span class="keyword">return</span> parameters, gradients, cost_list</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/04.png"><br>下面进行预测。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 进行预测</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">predict</span>(<span class="params">w, b, x_test</span>):</span></span><br><span class="line">    z = sigmoid(np.dot(w.T, x_test)+b)</span><br><span class="line">    Y_prediction = np.zeros((<span class="number">1</span>, x_test.shape[<span class="number">1</span>]))</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(z.shape[<span class="number">1</span>]):</span><br><span class="line">        <span class="keyword">if</span> z[<span class="number">0</span>, i] &lt;= <span class="number">0.5</span>:</span><br><span class="line">            Y_prediction[<span class="number">0</span>, i] = <span class="number">0</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            Y_prediction[<span class="number">0</span>, i] = <span class="number">1</span></span><br><span class="line">           </span><br><span class="line">    <span class="keyword">return</span> Y_prediction</span><br></pre></td></tr></table></figure>

<p>最后用测试数据进行预测。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">    <span class="comment"># 进行预测</span></span><br><span class="line">    y_pred_test = predict(parameters[<span class="string">&quot;weight&quot;</span>], parameters[<span class="string">&quot;bias&quot;</span>], x_test)</span><br><span class="line">    y_pred_train = predict(parameters[<span class="string">&quot;weight&quot;</span>], parameters[<span class="string">&quot;bias&quot;</span>], x_train)</span><br><span class="line">    <span class="comment"># 计算准确率</span></span><br><span class="line">    train_accuracy = <span class="number">100</span> - np.mean(np.<span class="built_in">abs</span>(y_pred_train - y_train))*<span class="number">100</span></span><br><span class="line">    test_accuracy = <span class="number">100</span> - np.mean(np.<span class="built_in">abs</span>(y_pred_test - y_test))*<span class="number">100</span></span><br><span class="line">    print(<span class="string">&quot;训练集预测准确率%f&quot;</span> % (train_accuracy))</span><br><span class="line">    print(<span class="string">&quot;测试集预测准确率%f&quot;</span> % (test_accuracy))</span><br><span class="line">训练集的准确率为<span class="number">93.68</span>%，测试集的准确率为<span class="number">95.16</span>%。</span><br><span class="line">    <span class="comment"># 用sklearn进行</span></span><br><span class="line">    <span class="keyword">from</span> sklearn <span class="keyword">import</span> linear_model</span><br><span class="line">    logreg = linear_model.LogisticRegression(random_state = <span class="number">42</span>, max_iter = <span class="number">150</span>)</span><br><span class="line">    print(<span class="string">&quot;sklearn算法&quot;</span>)</span><br><span class="line">    print(<span class="string">&quot;训练集预测准确率%f&quot;</span> % (logreg.fit(x_train.T, y_train.T).score(x_train.T, y_train.T)))</span><br><span class="line">    print(<span class="string">&quot;测试集预测准确率%f&quot;</span> % (logreg.fit(x_train.T, y_train.T).score(x_test.T, y_test.T)))</span><br></pre></td></tr></table></figure>
<p>准确率分别为100%和96.8%。</p>
<p>人工神经网络(Artificial Neural Network, ANN)<br>又称深度神经网络(deep neural network）或深度学习(deep learning)。最基础的人工神经网络为将逻辑回归进行至少两次。在逻辑回归中，只有输入层和输出层，而在神经网络中，有至少一个隐藏层在输入层和输出层之间。“深度(deep)”是隐藏层的层数很多，有多少是一个相对的概念，随着硬件的发展不断增加。“隐藏”的意思是它们不能直接看到输入的训练数据。<br>如下图，有一个隐藏层，这样的神经网络有2层，在计算层数的时候输入层被忽略。</p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/05.jpg"><br>隐藏层有3个节点，数量的选择是随意的，没有理由。节点的数量就像学习率一样，是一个超参数。输入和输出层的情况和逻辑回归中一样。其中用到了tanh函数，用作激活函数，比sigmoid产生的输出更加集中。它还能增加非线性，使得模型学习得更好。隐藏层是输入层的输出，是输出层的输入。<br>下面就来具体研究2层神经网络。<br>层数和参数的初始化。<br>将权重初始化为0.01，偏差为0。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 初始化参数和层数</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">init_nn_parameters</span>(<span class="params">x_train, y_train</span>):</span></span><br><span class="line">    parameters = &#123;</span><br><span class="line">        <span class="string">&quot;weight1&quot;</span> : np.random.randn(<span class="number">3</span>, x_train.shape[<span class="number">0</span>])*<span class="number">0.1</span>,</span><br><span class="line">        <span class="string">&quot;bias1&quot;</span> : np.zeros((<span class="number">3</span>, <span class="number">1</span>)),</span><br><span class="line">        <span class="string">&quot;weight2&quot;</span> : np.random.randn(y_train.shape[<span class="number">0</span>], <span class="number">3</span>)*<span class="number">0.1</span>,</span><br><span class="line">        <span class="string">&quot;bias2&quot;</span> : np.zeros((y_train.shape[<span class="number">0</span>], <span class="number">1</span>))</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> parameters</span><br></pre></td></tr></table></figure>
<p>前向传播过程与逻辑回归基本一样，唯一的不同采用tanh函数，进行两次。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 神经网络前向传播过程</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">fp_NN</span>(<span class="params">x_train, parameters</span>):</span></span><br><span class="line">    Z1 = np.dot(parameters[<span class="string">&quot;weight1&quot;</span>], x_train) + parameters[<span class="string">&quot;bias1&quot;</span>]</span><br><span class="line">    A1 = np.tanh(Z1)</span><br><span class="line">    Z2 = np.dot(parameters[<span class="string">&quot;weight2&quot;</span>], A1) + parameters[<span class="string">&quot;bias2&quot;</span>]</span><br><span class="line">    A2 = sigmoid(Z2)</span><br><span class="line">   </span><br><span class="line">    cache = &#123;</span><br><span class="line">        <span class="string">&quot;Z1&quot;</span> : Z1,</span><br><span class="line">        <span class="string">&quot;A1&quot;</span> : A1,</span><br><span class="line">        <span class="string">&quot;Z2&quot;</span> : Z2,</span><br><span class="line">        <span class="string">&quot;A2&quot;</span> : A2</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> A2, cache</span><br></pre></td></tr></table></figure>
<p>损失函数跟逻辑回归一样，用交叉熵函数。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 神经网络的损失函数</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">cost_NN</span>(<span class="params">A2, Y, parameters</span>):</span></span><br><span class="line">    logprobs = np.multiply(np.log(A2), Y)</span><br><span class="line">    cost = -np.<span class="built_in">sum</span>(logprobs)/Y.shape[<span class="number">1</span>]</span><br><span class="line">    <span class="keyword">return</span> cost</span><br></pre></td></tr></table></figure>

<p>后向传播过程，即意味着求导。要了解数学内容，去看其它材料吧。逻辑跟逻辑回归是一样的。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 神经网络后向传播过程</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">bp_NN</span>(<span class="params">parameters, cache, X, Y</span>):</span></span><br><span class="line">    dZ2 = cache[<span class="string">&quot;A2&quot;</span>] - Y</span><br><span class="line">    dW2 = np.dot(dZ2, cache[<span class="string">&quot;A1&quot;</span>].T)/X.shape[<span class="number">1</span>]</span><br><span class="line">    db2 = np.<span class="built_in">sum</span>(dZ2, axis = <span class="number">1</span>, keepdims = <span class="literal">True</span>)/X.shape[<span class="number">1</span>]</span><br><span class="line">    dZ1 = np.dot(parameters[<span class="string">&quot;weight2&quot;</span>].T, dZ2)*(<span class="number">1</span>-np.power(cache[<span class="string">&quot;A1&quot;</span>], <span class="number">2</span>))</span><br><span class="line">    dW1 = np.dot(dZ1, X.T)/X.shape[<span class="number">1</span>]</span><br><span class="line">    db1 = np.<span class="built_in">sum</span>(dZ1, axis = <span class="number">1</span>, keepdims = <span class="literal">True</span>)/X.shape[<span class="number">1</span>]</span><br><span class="line">    grads = &#123;</span><br><span class="line">        <span class="string">&quot;dweight1&quot;</span> : dW1,</span><br><span class="line">        <span class="string">&quot;dbias1&quot;</span> : db1,</span><br><span class="line">        <span class="string">&quot;dweight2&quot;</span> : dW2,</span><br><span class="line">        <span class="string">&quot;dbias2&quot;</span> : db2</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> grads</span><br></pre></td></tr></table></figure>

<p>更新参数，跟逻辑回归里一样的。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 更新神经网络参数</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">update_NN</span>(<span class="params">parameters, grads, learning_rate = <span class="number">0.01</span></span>):</span></span><br><span class="line">    parameters = &#123;</span><br><span class="line">        <span class="string">&quot;weight1&quot;</span> : parameters[<span class="string">&quot;weight1&quot;</span>] - learning_rate*grads[<span class="string">&quot;dweight1&quot;</span>],</span><br><span class="line">        <span class="string">&quot;bias1&quot;</span> : parameters[<span class="string">&quot;bias1&quot;</span>] - learning_rate*grads[<span class="string">&quot;dbias1&quot;</span>],</span><br><span class="line">        <span class="string">&quot;weight2&quot;</span> : parameters[<span class="string">&quot;weight2&quot;</span>] - learning_rate*grads[<span class="string">&quot;dweight2&quot;</span>],</span><br><span class="line">        <span class="string">&quot;bias2&quot;</span> : parameters[<span class="string">&quot;bias2&quot;</span>] - learning_rate*grads[<span class="string">&quot;dbias2&quot;</span>]</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> parameters</span><br></pre></td></tr></table></figure>

<p>进行预测</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 进行预测</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">predict_NN</span>(<span class="params">parameters, x_test</span>):</span></span><br><span class="line">    A2, cache = fp_NN(x_test, parameters)</span><br><span class="line">    Y_pred = np.zeros((<span class="number">1</span>, x_test.shape[<span class="number">1</span>]))</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(A2.shape[<span class="number">1</span>]):</span><br><span class="line">        <span class="keyword">if</span> A2[<span class="number">0</span>, i] &lt;= <span class="number">0.5</span>:</span><br><span class="line">            Y_pred[<span class="number">0</span>, i] = <span class="number">0</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            Y_pred[<span class="number">0</span>, i] = <span class="number">1</span></span><br><span class="line">            </span><br><span class="line">    <span class="keyword">return</span> Y_pred</span><br></pre></td></tr></table></figure>

<p>最后，建立神经网络</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 建立两层神经网络</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">NN</span>(<span class="params">x_train, y_train, x_test, y_test, num_iterations</span>):</span></span><br><span class="line">    cost_list = []</span><br><span class="line">    index_list = []</span><br><span class="line">    <span class="comment"># 初始化参数</span></span><br><span class="line">    parameters = init_nn_parameters(x_train, y_train)</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">0</span>, num_iterations):</span><br><span class="line">        A2, cache = fp_NN(x_train, parameters)</span><br><span class="line">        cost = cost_NN(A2, y_train, parameters)</span><br><span class="line">        grads = bp_NN(parameters, cache, x_train, y_train)</span><br><span class="line">        parameters = update_NN(parameters, grads)</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> i % <span class="number">100</span> == <span class="number">0</span>:</span><br><span class="line">            cost_list.append(cost)</span><br><span class="line">            index_list.append(i)</span><br><span class="line">            print(<span class="string">&quot;第%i次迭代后的成本:%f&quot;</span> % (i, cost))</span><br><span class="line">    </span><br><span class="line">    plt.figure()</span><br><span class="line">    plt.plot(index_list, cost_list)</span><br><span class="line">    plt.savefig(<span class="string">&quot;NN_LC.png&quot;</span>)</span><br><span class="line">    plt.close()</span><br><span class="line">    <span class="comment"># 进行预测</span></span><br><span class="line">    y_pred_test = predict_NN(parameters, x_test)</span><br><span class="line">    y_pred_train = predict_NN(parameters, x_train)</span><br><span class="line">    <span class="comment"># 计算准确率</span></span><br><span class="line">    train_accuracy = <span class="number">100</span> - np.mean(np.<span class="built_in">abs</span>(y_pred_train - y_train))*<span class="number">100</span></span><br><span class="line">    test_accuracy = <span class="number">100</span> - np.mean(np.<span class="built_in">abs</span>(y_pred_test - y_test))*<span class="number">100</span></span><br><span class="line">    print(<span class="string">&quot;训练集预测准确率%f&quot;</span> % (train_accuracy))</span><br><span class="line">    print(<span class="string">&quot;测试集预测准确率%f&quot;</span> % (test_accuracy))</span><br></pre></td></tr></table></figure>

<p>最后，看结果。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">parameters = NN(x_train, y_train, x_test, y_test, num_iterations = <span class="number">2500</span>)</span><br></pre></td></tr></table></figure>
<p>训练集预测准确率100.000000<br>测试集预测准确率95.161290<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/06.png"></p>
<p>不比逻辑回归好啊？<br>L层神经网络(L layer neural network)<br>当隐藏层数量增加是，它能探测到更复杂的特征。<br>有许多超参数需要我们选择，如学习率，隐藏层层数，迭代次数，激活函数类型等。<br>用keras实现L层神经网络，老调不对，先摆着，看第二篇文章，讲pytorch的。<br><a target="_blank" rel="noopener" href="https://www.kaggle.com/kanncaa1/pytorch-tutorial-for-deep-learning-lovers">https://www.kaggle.com/kanncaa1/pytorch-tutorial-for-deep-learning-lovers</a><br>pytorch是numpy的替代品，可以充分利用GPU的运算能力，是一个深度学习研究平台，提供了最大程度的扩展性和速度。<br>Pytorch基础<br>在pytorch中，矩阵（数组）被称为张量(tensors)。<br>先看numpy数组的例子</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># numpy数组</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">numpy_array</span>():</span></span><br><span class="line">    array = [[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>], [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>]]</span><br><span class="line">    first_array = np.array(array)</span><br><span class="line">    print(<span class="built_in">type</span>(first_array))</span><br><span class="line">    print(np.shape(first_array))</span><br><span class="line">    print(first_array)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;<span class="class"><span class="keyword">class</span> &#x27;<span class="title">numpy</span>.<span class="title">ndarray</span>&#x27;&gt;</span></span><br><span class="line"><span class="class">(<span class="params"><span class="number">2</span>, <span class="number">3</span></span>)</span></span><br><span class="line"><span class="class">[[1 2 3]</span></span><br><span class="line"><span class="class">[4 5 6]]</span></span><br></pre></td></tr></table></figure>
<p>下面看张量</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> torch</span><br><span class="line"><span class="comment"># 张量</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">pytorch_tensor</span>(<span class="params">array</span>):</span></span><br><span class="line">    tensor = torch.Tensor(array)</span><br><span class="line">    print(tensor.<span class="built_in">type</span>)</span><br><span class="line">    print(tensor.shape)</span><br><span class="line">    print(tensor)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;built-<span class="keyword">in</span> method <span class="built_in">type</span> of Tensor <span class="built_in">object</span> at <span class="number">0x7f555a14b690</span>&gt;</span><br><span class="line">torch.Size([<span class="number">2</span>, <span class="number">3</span>])</span><br><span class="line">tensor([[<span class="number">1.</span>, <span class="number">2.</span>, <span class="number">3.</span>],</span><br><span class="line">        [<span class="number">4.</span>, <span class="number">5.</span>, <span class="number">6.</span>]])</span><br></pre></td></tr></table></figure>

<p>张量与numpy数组的转换</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 张量与数组的转换</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">transform</span>():</span></span><br><span class="line">    array = np.random.rand(<span class="number">2</span>, <span class="number">2</span>)</span><br><span class="line">    print(<span class="string">&quot;&#123;&#125; &#123;&#125;\n&quot;</span>.<span class="built_in">format</span>(<span class="built_in">type</span>(array), array))</span><br><span class="line">    </span><br><span class="line">    from_numpy_to_tensor = torch.from_numpy(array)</span><br><span class="line">    print(<span class="string">&quot;&#123;&#125;\n&quot;</span>.<span class="built_in">format</span>(from_numpy_to_tensor))</span><br><span class="line">    </span><br><span class="line">    tensor = from_numpy_to_tensor</span><br><span class="line">    from_tensor_to_numpy = tensor.numpy()</span><br><span class="line">    print(<span class="string">&quot;&#123;&#125; &#123;&#125;\n&quot;</span>.<span class="built_in">format</span>(<span class="built_in">type</span>(from_tensor_to_numpy), from_tensor_to_numpy))</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&lt;<span class="class"><span class="keyword">class</span> &#x27;<span class="title">numpy</span>.<span class="title">ndarray</span>&#x27;&gt; [[0.22831416 0.2857514 ]</span></span><br><span class="line"><span class="class">[0.26072294 0.01614062]]</span></span><br><span class="line"><span class="class"></span></span><br><span class="line"><span class="class"></span></span><br><span class="line"><span class="class"><span class="title">tensor</span>(<span class="params">[[<span class="number">0.2283</span>, <span class="number">0.2858</span>],</span></span></span><br><span class="line"><span class="class"><span class="params">        [<span class="number">0.2607</span>, <span class="number">0.0161</span>]], dtype=torch.float64</span>)</span></span><br><span class="line"><span class="class"></span></span><br><span class="line"><span class="class"></span></span><br><span class="line"><span class="class">&lt;<span class="title">class</span> &#x27;<span class="title">numpy</span>.<span class="title">ndarray</span>&#x27;&gt; [[0.22831416 0.2857514 ]</span></span><br><span class="line"><span class="class">[0.26072294 0.01614062]]</span></span><br></pre></td></tr></table></figure>

<p>pytorch基础数学</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 基础数学</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">basic_math</span>():</span></span><br><span class="line">    <span class="comment"># 创建tensor</span></span><br><span class="line">    tensor = torch.ones(<span class="number">3</span>, <span class="number">3</span>)</span><br><span class="line">    print(<span class="string">&quot;\n&quot;</span>, tensor)</span><br><span class="line">    <span class="comment"># 改变大小</span></span><br><span class="line">    print(<span class="string">&quot;&#123;&#125;&#123;&#125;\n&quot;</span>.<span class="built_in">format</span>(tensor.view(<span class="number">9</span>).shape, tensor.view(<span class="number">9</span>)))</span><br><span class="line">    <span class="comment"># 加</span></span><br><span class="line">    print(<span class="string">&quot;加:&#123;&#125;\n&quot;</span>.<span class="built_in">format</span>(torch.add(tensor, tensor)))</span><br><span class="line">    <span class="comment"># 减</span></span><br><span class="line">    print(<span class="string">&quot;减:&#123;&#125;\n&quot;</span>.<span class="built_in">format</span>(tensor.sub(tensor)))</span><br><span class="line">    <span class="comment"># 乘</span></span><br><span class="line">    print(<span class="string">&quot;乘:&#123;&#125;\n&quot;</span>.<span class="built_in">format</span>(torch.mul(tensor, tensor)))</span><br><span class="line">    <span class="comment"># 除</span></span><br><span class="line">    print(<span class="string">&quot;除:&#123;&#125;\n&quot;</span>.<span class="built_in">format</span>(torch.div(tensor, tensor)))</span><br><span class="line">    <span class="comment"># 均值</span></span><br><span class="line">    tensor = torch.Tensor([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>])</span><br><span class="line">    print(<span class="string">&quot;均值:&#123;&#125;&quot;</span>.<span class="built_in">format</span>(tensor.mean()))</span><br><span class="line">    <span class="comment"># 均值</span></span><br><span class="line">    print(<span class="string">&quot;标准差:&#123;&#125;&quot;</span>.<span class="built_in">format</span>(tensor.std()))</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">tensor([[<span class="number">1.</span>, <span class="number">1.</span>, <span class="number">1.</span>],</span><br><span class="line">        [<span class="number">1.</span>, <span class="number">1.</span>, <span class="number">1.</span>],</span><br><span class="line">        [<span class="number">1.</span>, <span class="number">1.</span>, <span class="number">1.</span>]])</span><br><span class="line">torch.Size([<span class="number">9</span>])tensor([<span class="number">1.</span>, <span class="number">1.</span>, <span class="number">1.</span>, <span class="number">1.</span>, <span class="number">1.</span>, <span class="number">1.</span>, <span class="number">1.</span>, <span class="number">1.</span>, <span class="number">1.</span>])</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">加:tensor([[<span class="number">2.</span>, <span class="number">2.</span>, <span class="number">2.</span>],</span><br><span class="line">        [<span class="number">2.</span>, <span class="number">2.</span>, <span class="number">2.</span>],</span><br><span class="line">        [<span class="number">2.</span>, <span class="number">2.</span>, <span class="number">2.</span>]])</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">减:tensor([[<span class="number">0.</span>, <span class="number">0.</span>, <span class="number">0.</span>],</span><br><span class="line">        [<span class="number">0.</span>, <span class="number">0.</span>, <span class="number">0.</span>],</span><br><span class="line">        [<span class="number">0.</span>, <span class="number">0.</span>, <span class="number">0.</span>]])</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">乘:tensor([[<span class="number">1.</span>, <span class="number">1.</span>, <span class="number">1.</span>],</span><br><span class="line">        [<span class="number">1.</span>, <span class="number">1.</span>, <span class="number">1.</span>],</span><br><span class="line">        [<span class="number">1.</span>, <span class="number">1.</span>, <span class="number">1.</span>]])</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">除:tensor([[<span class="number">1.</span>, <span class="number">1.</span>, <span class="number">1.</span>],</span><br><span class="line">        [<span class="number">1.</span>, <span class="number">1.</span>, <span class="number">1.</span>],</span><br><span class="line">        [<span class="number">1.</span>, <span class="number">1.</span>, <span class="number">1.</span>]])</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">均值:<span class="number">3.0</span></span><br><span class="line">标准差:<span class="number">1.5811388492584229</span></span><br></pre></td></tr></table></figure>

<p>变量(Variables)<br>它能积累梯度。在神经网络的反向传播过程中，我们将计算梯度。因此我们需要处理梯度。变量与张量的区别是变量能够自动累积梯度。变量同样的也能进行那些数学运算。为了完成反向传播我们需要变量。<br>假设我们有方程y = x^2，定义变量x = [2,4]，计算后我们发现y = [4,16]，Recap o方程（Recap o equation，不知道咋翻）是o = (1/2)sum(y) = (1/2)sum(x^2)，o的导数为o = x，因此梯度为[2,4]。下面用程序来实现。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> torch.autograd <span class="keyword">import</span> Variable</span><br><span class="line"><span class="comment"># 求y = x^2 在x = [2, 4]的梯度</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">grad</span>():</span></span><br><span class="line">    var = Variable(torch.ones(<span class="number">3</span>), requires_grad = <span class="literal">True</span>)</span><br><span class="line">    print(var)</span><br><span class="line">    array = [<span class="number">2</span>, <span class="number">4</span>]</span><br><span class="line">    tensor = torch.Tensor(array)</span><br><span class="line">    x = Variable(tensor, requires_grad = <span class="literal">True</span>)</span><br><span class="line">    y = x**<span class="number">2</span></span><br><span class="line">    print(<span class="string">&quot;y=&quot;</span>, y)</span><br><span class="line">   </span><br><span class="line">    o = (<span class="number">1</span>/<span class="number">2</span>)*<span class="built_in">sum</span>(y)</span><br><span class="line">    print(<span class="string">&quot;o=&quot;</span>, o)</span><br><span class="line">   </span><br><span class="line">    <span class="comment"># 反向传播</span></span><br><span class="line">    o.backward()</span><br><span class="line">   </span><br><span class="line">    print(<span class="string">&quot;梯度:&quot;</span>, x.grad)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">tensor([<span class="number">1.</span>, <span class="number">1.</span>, <span class="number">1.</span>], requires_grad=<span class="literal">True</span>)</span><br><span class="line">y= tensor([ <span class="number">4.</span>, <span class="number">16.</span>], grad_fn=&lt;PowBackward0&gt;)</span><br><span class="line">o= tensor(<span class="number">10.</span>, grad_fn=&lt;MulBackward0&gt;)</span><br><span class="line">梯度: tensor([<span class="number">2.</span>, <span class="number">4.</span>])</span><br></pre></td></tr></table></figure>

<p>线性回归<br>y = Ax + B，A为直线斜率，B为偏差值（y截距）。<br>一个例子：车的价格和销量。<br>先初始化数据，画图看看。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 线性回归的例子</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">linear_regress</span>():</span></span><br><span class="line">    <span class="comment"># 车价</span></span><br><span class="line">    car_prices_array = [<span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>]</span><br><span class="line">    car_price_np = np.array(car_prices_array, dtype = np.float32)</span><br><span class="line">    car_price_np = car_price_np.reshape(-<span class="number">1</span>, <span class="number">1</span>)</span><br><span class="line">    car_price_tensor = Variable(torch.from_numpy(car_price_np))</span><br><span class="line">    <span class="comment"># 车销量</span></span><br><span class="line">    number_of_car_sell_array = [<span class="number">7.5</span>, <span class="number">7</span>, <span class="number">6.5</span>, <span class="number">6.0</span>, <span class="number">5.5</span>, <span class="number">5.0</span>, <span class="number">4.5</span>]</span><br><span class="line">    number_of_car_sell_np = np.array(number_of_car_sell_array, dtype = np.float32)</span><br><span class="line">    number_of_car_sell_np = number_of_car_sell_np.reshape(-<span class="number">1</span>, <span class="number">1</span>)</span><br><span class="line">    number_of_car_sell_tensor = Variable(torch.from_numpy(number_of_car_sell_np))</span><br><span class="line">    <span class="comment"># 可视化</span></span><br><span class="line">    plt.figure()</span><br><span class="line">    plt.scatter(car_prices_array, number_of_car_sell_array)</span><br><span class="line">    plt.savefig(<span class="string">&quot;./output/price_sell.png&quot;</span>)</span><br></pre></td></tr></table></figure>

<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/07.png"></p>
<p>现在要问当车价为100时的销量。用线性回归来解决。要用直线来拟合这些数据，目标是误差最小。<br>线性回归的步骤：<br>①创建线性回归类。<br>②从线性回归类定义模型。<br>③计算MSE：平均误差平方（Mean Squared Error）<br>④优化SGD:随机梯度下降（Stochastic Gradient Descent）<br>⑤反向传播过程。<br>⑥预测。<br>下面用Pytorch实现。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LinearRegression</span>(<span class="params">nn.Module</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, input_size, output_size</span>):</span></span><br><span class="line">        <span class="built_in">super</span>(LinearRegression, self).__init__()</span><br><span class="line">        self.linear = nn.Linear(input_size, output_size)</span><br><span class="line">   </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">forward</span>(<span class="params">self, x</span>):</span></span><br><span class="line">        <span class="keyword">return</span> self.linear(x)</span><br><span class="line">       </span><br><span class="line">input_dim = <span class="number">1</span></span><br><span class="line">output_dim = <span class="number">1</span></span><br><span class="line">model = LinearRegression(input_dim, output_dim)</span><br><span class="line">loss_fn = nn.MSELoss()</span><br><span class="line">   </span><br><span class="line"><span class="comment"># 优化器</span></span><br><span class="line">learning_rate = <span class="number">0.02</span></span><br><span class="line">optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate)</span><br><span class="line">   </span><br><span class="line"><span class="comment"># 训练模型</span></span><br><span class="line">loss_list = []</span><br><span class="line">iteration_number = <span class="number">1001</span></span><br><span class="line"><span class="keyword">for</span> iteration <span class="keyword">in</span> <span class="built_in">range</span>(iteration_number):</span><br><span class="line">    <span class="comment"># 优化</span></span><br><span class="line">    optimizer.zero_grad()</span><br><span class="line">    <span class="comment"># 前向传播获得输出</span></span><br><span class="line">    results = model(car_price_tensor)</span><br><span class="line">    <span class="comment"># 计算损失</span></span><br><span class="line">    loss = loss_fn(results, number_of_car_sell_tensor)</span><br><span class="line">    <span class="comment"># 反向传播</span></span><br><span class="line">    loss.backward()</span><br><span class="line">    <span class="comment"># 更新参数</span></span><br><span class="line">    optimizer.step()</span><br><span class="line">    <span class="comment"># 保存损失值</span></span><br><span class="line">    loss_list.append(loss.data)</span><br><span class="line">    <span class="comment"># 打印损失值</span></span><br><span class="line">    <span class="keyword">if</span> iteration % <span class="number">50</span> == <span class="number">0</span>:</span><br><span class="line">        print(<span class="string">&quot;epoch &#123;&#125;, loss &#123;&#125;&quot;</span>.<span class="built_in">format</span>(iteration, loss.data))</span><br><span class="line">       </span><br><span class="line"><span class="comment"># 画图</span></span><br><span class="line">plt.figure()</span><br><span class="line">plt.plot(<span class="built_in">range</span>(iteration_number), loss_list)</span><br><span class="line">plt.savefig(<span class="string">&quot;./output/lr_curve.png&quot;</span>)</span><br></pre></td></tr></table></figure>

<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/08.png"></p>
<p>进行了1001次迭代。在1000次迭代后，损失接近为0。现在进行预测。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 进行预测</span></span><br><span class="line">predicted = model(car_price_tensor).data.numpy()</span><br><span class="line">plt.figure()</span><br><span class="line">plt.scatter(car_prices_array, number_of_car_sell_array, color = <span class="string">&quot;red&quot;</span>)</span><br><span class="line">plt.scatter(car_prices_array, predicted, color = <span class="string">&quot;blue&quot;</span>)</span><br><span class="line">plt.savefig(<span class="string">&quot;./output/result.png&quot;</span>)</span><br><span class="line">plt.close()</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/09.png"></p>
<p>逻辑回归<br>对于分类问题，线性回归表现并不好。<br>线性回归+逻辑方程(softmax)=逻辑回归。<br>步骤:<br>①导入库。<br>②准备数据，采用MNIST，是一些标记为0-9十个数字的28×28的图片，把其转换为一维的256个数据，划分为训练集和测试集，创建tensor变量。batch_size的意思:例如我们有1000个样本，可以把1000个样本拿到一起训练，也可以把样本划分为10组，每组100个样本，依次进行10次训练。batch_size是每组的样本量，在这个例子中，等于100。确定迭代次数(epoch)，即把所有样本训练一次。在本例中，有33600个样本，训练一次要训练33600个样本，分成了336组，进行29次迭代，一共的迭代次数是9744次(接近10000次)。使用TensorDataset()封装数据。DataLoader()将数据和样本结合到一起，也提供了对数据的并行迭代功能。将数据可视化。<br>③创建逻辑回归模型。<br>④实例化模型。<br>输入维度2828， 输出维度10。<br>⑤计算损失，采用交叉熵(Cross entropy loss)。<br>⑥定义优化器，采用SGD优化器。<br>⑦训练模型。<br>⑧预测。</p>
<p>程序调不对，用<a target="_blank" rel="noopener" href="https://blog.csdn.net/a946971688/article/details/89671885">另一个</a></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 逻辑回归的例子</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">logistic_regress2</span>():</span></span><br><span class="line">    <span class="keyword">import</span> torch</span><br><span class="line">    <span class="keyword">import</span> torch.nn <span class="keyword">as</span> nn</span><br><span class="line">    <span class="keyword">import</span> torchvision</span><br><span class="line">    <span class="keyword">import</span> torchvision.transforms <span class="keyword">as</span> transforms</span><br><span class="line">    <span class="keyword">from</span> torchvision.datasets <span class="keyword">import</span> MNIST</span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 定义超参数</span></span><br><span class="line">    input_size = <span class="number">784</span>    <span class="comment">#输入层神经元大小</span></span><br><span class="line">    num_classes = <span class="number">10</span> <span class="comment">#图像类别</span></span><br><span class="line">    num_epochs = <span class="number">25</span>  <span class="comment">#迭代次数</span></span><br><span class="line">    batch_size = <span class="number">100</span>   <span class="comment">#每次训练取得样本数</span></span><br><span class="line">    learning_rate = <span class="number">0.05</span> <span class="comment">#学习率</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 加载数据</span></span><br><span class="line">    train_dataset = torchvision.datasets.MNIST(root=<span class="string">&#x27;./&#x27;</span>, train=<span class="literal">True</span>, transform=transforms.ToTensor(), download=<span class="literal">True</span>)</span><br><span class="line">    test_dataset = torchvision.datasets.MNIST(root=<span class="string">&#x27;./&#x27;</span>, train=<span class="literal">False</span>, transform=transforms.ToTensor(), download=<span class="literal">True</span>)</span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 创建dataloader</span></span><br><span class="line">    train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=<span class="literal">True</span>)</span><br><span class="line">    test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=<span class="literal">True</span>)</span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 创建模型</span></span><br><span class="line">    model = nn.Linear(input_size, num_classes)</span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 损失函数和优化器</span></span><br><span class="line">    loss_fn = nn.CrossEntropyLoss()<span class="comment">#交叉熵损失函数</span></span><br><span class="line">    optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate)</span><br><span class="line">    <span class="comment"># 训练模型</span></span><br><span class="line">    loss_list = []</span><br><span class="line">    total_step = <span class="built_in">len</span>(train_loader)</span><br><span class="line">    <span class="keyword">for</span> epoch <span class="keyword">in</span> <span class="built_in">range</span>(num_epochs):</span><br><span class="line">        <span class="keyword">for</span> i, (images, labels) <span class="keyword">in</span> <span class="built_in">enumerate</span>(train_loader):</span><br><span class="line">            <span class="comment"># 将数据变换为[每批大小, 图像大小]</span></span><br><span class="line">            images = images.reshape(-<span class="number">1</span>, <span class="number">28</span>*<span class="number">28</span>)</span><br><span class="line">            </span><br><span class="line">            <span class="comment"># 前向传播</span></span><br><span class="line">            outputs = model(images)</span><br><span class="line">            loss = loss_fn(outputs, labels)</span><br><span class="line">            loss_list.append(loss)</span><br><span class="line">            </span><br><span class="line">            <span class="comment"># 反向传播</span></span><br><span class="line">            optimizer.zero_grad()</span><br><span class="line">            loss.backward()</span><br><span class="line">            optimizer.step()</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">if</span> (i+<span class="number">1</span>) % <span class="number">100</span> == <span class="number">0</span>:</span><br><span class="line">                <span class="built_in">print</span> (<span class="string">&#x27;Epoch [&#123;&#125;/&#123;&#125;], Step [&#123;&#125;/&#123;&#125;], Loss: &#123;:.4f&#125;&#x27;</span> .<span class="built_in">format</span>(epoch+<span class="number">1</span>, num_epochs, i+<span class="number">1</span>, total_step, loss.item()))</span><br><span class="line">                </span><br><span class="line">    plt.figure()</span><br><span class="line">    plt.plot(loss_list)</span><br><span class="line">    plt.savefig(<span class="string">&quot;./output/lr_loss.png&quot;</span>)</span><br><span class="line">    plt.close()</span><br><span class="line">                </span><br><span class="line">    <span class="comment"># 测试</span></span><br><span class="line">    <span class="keyword">with</span> torch.no_grad():</span><br><span class="line">        correct = <span class="number">0</span></span><br><span class="line">        total = <span class="number">0</span></span><br><span class="line">        <span class="keyword">for</span> images, labels <span class="keyword">in</span> test_loader:</span><br><span class="line">            images = images.reshape(-<span class="number">1</span>, <span class="number">28</span>*<span class="number">28</span>)</span><br><span class="line">            outputs = model(images)</span><br><span class="line">            _, pred = torch.<span class="built_in">max</span>(outputs.data, <span class="number">1</span>)</span><br><span class="line">            total += labels.size()[<span class="number">0</span>]</span><br><span class="line">            correct += (pred == labels).<span class="built_in">sum</span>()</span><br><span class="line">            </span><br><span class="line">        print(<span class="string">&quot;模型预测准确率&#123;&#125;%&quot;</span>.<span class="built_in">format</span>(<span class="number">100</span>*correct.item()/total))</span><br></pre></td></tr></table></figure>
<p>模型准确率92%。</p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/10.png"></p>
<p>人工神经网络(Artificial Neural Network, ANN)<br>逻辑回归处理分类问题很好，但当复杂性(非线性)增加时，模型准确性下降。为了增加模型的复杂性，需要增加更多的非线性函数的隐藏层。<br>具体步骤:<br>①导入库。<br>②准备数据。<br>③创建ANN模型:增加三个隐藏层，用ReLU, Tanh和ELU做为激活函数。<br>④实例化模型。隐藏层维度150，随便选的。这也是超参数之一。<br>⑤选择损失函数，跟逻辑回归一样。<br>⑥优化器也一样。<br>⑦训练模型。<br>⑧预测。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 人工神经网络</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">ANN</span>():</span></span><br><span class="line">    <span class="keyword">import</span> torch</span><br><span class="line">    <span class="keyword">import</span> torch.nn <span class="keyword">as</span> nn</span><br><span class="line">    <span class="keyword">from</span> torch.autograd <span class="keyword">import</span> Variable</span><br><span class="line">    <span class="keyword">from</span> torch.utils.data <span class="keyword">import</span> DataLoader</span><br><span class="line">    <span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line">    <span class="keyword">from</span> sklearn.model_selection <span class="keyword">import</span> train_test_split</span><br><span class="line">    <span class="keyword">import</span> os</span><br><span class="line">    <span class="keyword">import</span> torchvision</span><br><span class="line">    <span class="keyword">import</span> torchvision.transforms <span class="keyword">as</span> transforms</span><br><span class="line">    <span class="keyword">from</span> torchvision.datasets <span class="keyword">import</span> MNIST</span><br><span class="line">    </span><br><span class="line">    print(<span class="string">&quot;ANN\n&quot;</span>)</span><br><span class="line">    <span class="comment"># print(os.getcwd())</span></span><br><span class="line">    <span class="comment"># 加载数据</span></span><br><span class="line">    train_dataset = torchvision.datasets.MNIST(root=<span class="string">&#x27;./&#x27;</span>, train=<span class="literal">True</span>, transform=transforms.ToTensor(), download=<span class="literal">True</span>)</span><br><span class="line">    test_dataset = torchvision.datasets.MNIST(root=<span class="string">&#x27;./&#x27;</span>, train=<span class="literal">False</span>, transform=transforms.ToTensor(), download=<span class="literal">True</span>)</span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 定义超参数</span></span><br><span class="line">    batch_size = <span class="number">100</span></span><br><span class="line">    num_epochs = <span class="number">100</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 创建dataloader</span></span><br><span class="line">    train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=<span class="literal">True</span>)</span><br><span class="line">    test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 定义模型</span></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">ANNModel</span>(<span class="params">nn.Module</span>):</span></span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, input_dim, hidden_dim, output_dim</span>):</span></span><br><span class="line">            <span class="built_in">super</span>(ANNModel, self).__init__()</span><br><span class="line">            <span class="comment"># 第一层 784-&gt;150</span></span><br><span class="line">            self.fc1 = nn.Linear(input_dim, hidden_dim)</span><br><span class="line">            <span class="comment"># 非线性成分</span></span><br><span class="line">            self.relu1 = nn.ReLU()</span><br><span class="line">            <span class="comment"># 第二层 150-150</span></span><br><span class="line">            self.fc2 = nn.Linear(hidden_dim, hidden_dim)</span><br><span class="line">            <span class="comment"># 非线性成分</span></span><br><span class="line">            self.tanh2 = nn.Tanh()</span><br><span class="line">            <span class="comment"># 第三层 150-150</span></span><br><span class="line">            self.fc3 = nn.Linear(hidden_dim, hidden_dim)</span><br><span class="line">            <span class="comment"># 非线性成分</span></span><br><span class="line">            self.elu3 = nn.ELU()</span><br><span class="line">            <span class="comment"># 第四层 150-10</span></span><br><span class="line">            self.fc4 = nn.Linear(hidden_dim, output_dim)</span><br><span class="line">            </span><br><span class="line">        <span class="comment"># 前向传播</span></span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">forward</span>(<span class="params">self, x</span>):</span></span><br><span class="line">            out = self.fc1(x)</span><br><span class="line">            out = self.relu1(out)</span><br><span class="line">            out = self.fc2(out)</span><br><span class="line">            out = self.tanh2(out)</span><br><span class="line">            out = self.fc3(out)</span><br><span class="line">            out = self.elu3(out)</span><br><span class="line">            out = self.fc4(out)</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">return</span> out</span><br><span class="line">            </span><br><span class="line">    <span class="comment"># 初始化ANN</span></span><br><span class="line">    input_dim = <span class="number">28</span>*<span class="number">28</span></span><br><span class="line">    hidden_dim = <span class="number">150</span> <span class="comment"># 这个可以调参的</span></span><br><span class="line">    output_dim = <span class="number">10</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 创建ANN</span></span><br><span class="line">    model = ANNModel(input_dim, hidden_dim, output_dim)</span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 超参数</span></span><br><span class="line">    loss_fn = nn.CrossEntropyLoss()</span><br><span class="line">    learning_rate = <span class="number">0.02</span></span><br><span class="line">    optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate) </span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 训练ANN</span></span><br><span class="line">    count = <span class="number">0</span></span><br><span class="line">    loss_list = []</span><br><span class="line">    iteration_list = []</span><br><span class="line">    accuracy_list = []</span><br><span class="line">    <span class="keyword">for</span> epoch <span class="keyword">in</span> <span class="built_in">range</span>(num_epochs):</span><br><span class="line">        <span class="keyword">for</span> i, (images, labels) <span class="keyword">in</span> <span class="built_in">enumerate</span>(train_loader):</span><br><span class="line">            <span class="comment"># print(epoch, i)</span></span><br><span class="line">            train = images.reshape(-<span class="number">1</span>, <span class="number">28</span>*<span class="number">28</span>)</span><br><span class="line">            labels = Variable(labels)</span><br><span class="line">            <span class="comment"># 梯度清零</span></span><br><span class="line">            optimizer.zero_grad()</span><br><span class="line">            <span class="comment"># 前向过程</span></span><br><span class="line">            outputs = model(train)</span><br><span class="line">            <span class="comment"># 计算损失</span></span><br><span class="line">            loss = loss_fn(outputs, labels)</span><br><span class="line">            <span class="comment"># 计算梯度</span></span><br><span class="line">            loss.backward()</span><br><span class="line">            <span class="comment"># 更新参数</span></span><br><span class="line">            optimizer.step()</span><br><span class="line">            </span><br><span class="line">            count += <span class="number">1</span></span><br><span class="line">            <span class="keyword">if</span> count % <span class="number">50</span> == <span class="number">0</span>:</span><br><span class="line">                <span class="comment"># 计算准确率</span></span><br><span class="line">                correct = <span class="number">0</span></span><br><span class="line">                total = <span class="number">0</span></span><br><span class="line">                <span class="keyword">for</span> images, labels <span class="keyword">in</span> test_loader:</span><br><span class="line">                    test = images.reshape(-<span class="number">1</span>, <span class="number">28</span>*<span class="number">28</span>)</span><br><span class="line">                    outputs = model(test)</span><br><span class="line">                    pred = torch.<span class="built_in">max</span>(outputs.data, <span class="number">1</span>)[<span class="number">1</span>]</span><br><span class="line">                    total += <span class="built_in">len</span>(labels)</span><br><span class="line">                    correct += (pred == labels).<span class="built_in">sum</span>()</span><br><span class="line">                    accuracy = <span class="number">100</span>*correct/<span class="built_in">float</span>(total)</span><br><span class="line">                loss_list.append(loss.data)</span><br><span class="line">                iteration_list.append(count)</span><br><span class="line">                accuracy_list.append(accuracy)</span><br><span class="line">            <span class="keyword">if</span> count % <span class="number">500</span> == <span class="number">0</span>:</span><br><span class="line">                print(<span class="string">&#x27;迭代次数: &#123;&#125;  损失: &#123;&#125;  准确率: &#123;&#125; %&#x27;</span>.<span class="built_in">format</span>(count, loss.data, accuracy))</span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 结果可视化</span></span><br><span class="line">    plt.figure()</span><br><span class="line">    plt.plot(iteration_list,loss_list)</span><br><span class="line">    plt.title(<span class="string">&quot;ANN loss&quot;</span>)</span><br><span class="line">    plt.savefig(<span class="string">&quot;./output/ANN_loss.png&quot;</span>)</span><br><span class="line">    plt.figure()</span><br><span class="line">    plt.plot(iteration_list,accuracy_list,color = <span class="string">&quot;red&quot;</span>)</span><br><span class="line">    plt.title(<span class="string">&quot;ANN accuracy&quot;</span>)</span><br><span class="line">    plt.savefig(<span class="string">&quot;./output/ANN_accuracy.png&quot;</span>)</span><br><span class="line">    plt.close()</span><br></pre></td></tr></table></figure>
<p>结果，正确率97.8%，花了大概一小时。</p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/11.png"><br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0234-dp/12.png"></p>
<p>还有卷积神经网络，图像处理用得比较多，先pass了。<br>总结一下，机器学习也好，深度学习也好，其实质都是拟合数据，拟合的方法(模型)不一样而已。用已知数据训练模型(求出一组参数)，然后用模型对未知数据做出预测。深度学习的模型是神经网络，由神经节组成。每个神经节接受若干输入，经过激活函数(通常为非线性函数，以拟合非线性关系)，产生一个输出。若干个神经节形成一层，前一层的输出作为下一层的输入，一直向前传递直到输出层。用输出结果与真实值对比(用损失函数)计算出损失值(前向传播)。接着，用梯度下降的方法沿着路径反向计算使损失值最小的参数，并更新参数(反向传播)。上述步骤重复若干次，损失值和预测准确率收敛到一定程度，即停止训练，运用模型进行预测。<br>整个过程，pytorch等框架为我们做了什么呢？数据准备(tensor，便于GPU运算; Variable，自动进行梯度运算并保存结果;dataLoader，便于分组训练)、定义模型(nn.Module，定义神经网络结构，定义前向传播过程，计算出输出值)、进行训练(Optimizer，梯度清零，更新参数;model，前向传播过程，计算输出值;提供损失函数:计算损失值，反向传播过程:backward)。其中核心是自动求导的过程。tensorflow我没了解过，应该也差不多。<br>这几天听了一个自己实现深度网络框架的课，正在整理笔记，下次奉上。<br>本文<a target="_blank" rel="noopener" href="https://github.com/zwdnet/JSMPwork/blob/main/DP.py">代码</a></p>
<p>我发文章的三个地方，欢迎大家在朋友圈等地方分享，欢迎点“在看”。<br>我的个人博客地址：<a href="https://zwdnet.github.io/">https://zwdnet.github.io</a><br>我的知乎文章地址： <a target="_blank" rel="noopener" href="https://www.zhihu.com/people/zhao-you-min/posts">https://www.zhihu.com/people/zhao-you-min/posts</a><br>我的微信个人订阅号：赵瑜敏的口腔医学学习园地</p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg"></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欢迎打赏！感谢支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/mm_facetoface_collect_qrcode_1542944836634.png" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/1542944857770.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="tag"># 学习笔记</a>
          
            <a href="/tags/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" rel="tag"># 量化投资</a>
          
            <a href="/tags/kaggle%E7%AB%9E%E8%B5%9B/" rel="tag"># kaggle竞赛</a>
          
            <a href="/tags/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/" rel="tag"># 深度学习</a>
          
            <a href="/tags/pytorch/" rel="tag"># pytorch</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2021/01/16/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B097%E2%80%94%E2%80%94kaggle%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E6%AF%94%E8%B5%9B%E8%AE%B0%E5%BD%956-%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0%E6%A8%A1%E5%9E%8B/" rel="next" title="量化投资学习笔记97——kaggle量化投资比赛记录6-深度学习模型">
                <i class="fa fa-chevron-left"></i> 量化投资学习笔记97——kaggle量化投资比赛记录6-深度学习模型
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2021/01/23/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B099%E2%80%94%E2%80%94%E5%88%9B%E9%80%A0%E4%BD%A0%E7%9A%84%E7%AC%AC%E4%B8%80%E4%B8%AA%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0%E6%A1%86%E6%9E%B6/" rel="prev" title="量化投资学习笔记99——创造你的第一个深度学习框架">
                量化投资学习笔记99——创造你的第一个深度学习框架 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTA2Mi8xNzU4Nw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%20%7C%7C%20archive">
              
                  <span class="site-state-item-count">452</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">29</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">544</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">本站版权归赵瑜敏所有，如欲转载请与本人联系。</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">1225.8k</span>
  
</div>









<div>
  <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1275447216'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s11.cnzz.com/z_stat.php%3Fid%3D1275447216%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"));</script>
</div>

        







  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1275447216&web_id=1275447216" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

  
</body>
</html>
